// pages/coinCertificate/coinCertificate.js
import api from '../../config/api'
import request from '../../utils/request'
import { shareOptions, getUserPermissions } from '../../utils/access'
import { removeStorage, getStorage } from '../../utils/utils'
Page({
  /**
   * 页面的初始数据
   */
  data: {
    clickOrderInfo: {},
    // tab切换变量 1:未兑换 2：已兑换
    isShow: 1,
    // 优惠券数组
    noConversionData: [],
    // 已兑换优惠券数组
    ConversionData: [],
    // 优惠券的ID
    id: null,
    // 当前页码值
    current: 1,
    // 数据总数量
    total: 0,
    // 已兑换列表是否加载完成
    isLoaing: false,
    // 来源数据
    sourceList: {},
    // 客服弹窗-整体二维码
    serviceQrcode:
      'https://image-classify.daieco.com/kejian-quanzi/mrm4Z9LEuSF514052d3cebf4e5fff095132b1eb81863.png',
    // 单独二维码
    qrcode:
      'https://image-classify.daieco.com/kejian-quanzi/Iwh5x26q9vzA8a6cd3e1aacd48a9a17f14cd314cd7fb.png',
  },
  // 1.0 Tab未兑换点击事件
  noConversion() {
    console.log('未兑换')
    this.setData({
      isShow: 1,
      noConversionData: [],
      ConversionData: [],
      current: 1,
    })
    // 调用获取优惠劵列表，重新刷新页面
    this.getUserDiscount()
  },
  // 1.1 未兑换立即使用按钮---携带券码id跳转券码页面
  go(e) {
    console.log('e', e)
    const { id, goodsid, couponname, tabtypeflag } = e.target.dataset
    console.log('tabTypeFlag', tabtypeflag)
    wx.navigateTo({
      url: `/pages/coinCertificateImg/coinCertificateImg?id=${id}&goodsId=${goodsid}&couponName=${couponname}&tabTypeFlag=${tabtypeflag}`,
    })
  },
  // 2.0 Tab 已兑换点击事件
  conversion() {
    console.log('已兑换')
    this.setData({
      isShow: 2,
      noConversionData: [],
      ConversionData: [],
      current: 1,
    })
    // 调用获取优惠劵列表，重新刷新页面
    this.getUserDiscount()
  },
  // 2.1 已兑换点击事件---回到未兑换列表，重新刷新列表
  return() {
    // 2.2 设置变量为未兑换的条件，重新调用方法，渲染页面
    console.log(1)
  },

  // 获取来源列表
  async getSourceList() {
    let res = await request.get(
      api.certificateSourceList,
      {},
      { loading: false }
    )
    if (res.httpStatus === 200) {
      this.setData({
        sourceList: res.data || {},
      })
      this.getUserDiscount()
    }
  },
  // 3.1 获取用户优惠券列表
  async getUserDiscount() {
    const { isShow, current, noConversionData, ConversionData, sourceList } =
      this.data
    console.log(isShow)
    const res = await request.get(
      api.userDiscount,
      {
        checkStatus: isShow,
        page: current,
      },
      { loading: false }
    )
    // 3.2 判断显示的是哪个页面
    console.log(isShow)
    res.data?.records.map((item, index) => {
      item.origin = sourceList[item.source]
    })
    if (isShow === 1) {
      this.setData({
        current: res.data.current,
        noConversionData:
          current === 1
            ? res.data?.records || []
            : [...noConversionData, ...res.data?.records],
        isLoaing: true,
        total: res.data.total,
      })
    } else {
      this.setData({
        current: res.data.current,
        ConversionData:
          current === 1
            ? res.data?.records || []
            : [...ConversionData, ...res.data?.records],
        isLoaing: false,
        total: res.data.total,
      })
    }
    console.log(res)
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // 清除缓存中未查看兑换券数量
    if (getStorage('newCouponNum')) {
      // 请求接口去除红点
      this.hideRedPoint()
    }
  },
  // 去除优惠券红点
  async hideRedPoint() {
    const res = await request.get(
      api.removeCoupon,
      {},
      {
        loading: false,
        modal: false,
      }
    )
    if (res.httpStatus === 200) {
      removeStorage('newCouponNum')
    }
  },
  closeModal: function () {
    this.wuliuModal.hide()
  },
  // 复制订单编号
  copyOrderNumber: function (e) {
    let { expressNo } = this.data.clickOrderInfo
    wx.setClipboardData({
      data: expressNo,
      success: () => {
        wx.showToast({
          title: '已复制',
          icon: 'none',
        })
      },
    })
  },
  // 点击物流状态
  showStatus: function (e) {
    console.log('e', e)
    let { info } = e.currentTarget.dataset
    this.setData({
      clickOrderInfo: { ...info },
    })
    this.wuliuModal.show()
  },
  // 保存图片
  handleSavePhoto() {
    wx.getImageInfo({
      src: this.data.serviceQrcode,
      success: function (sres) {
        // 调用系统方法，下载图片并保存
        getUserPermissions(
          'writePhotosAlbum',
          (res) => {
            if (res) {
              wx.showToast({
                title: '保存成功',
                icon: 'success',
              })
            } else {
              wx.showToast({
                title: '保存失败',
                icon: 'error',
              })
            }
          },
          { filePath: sres.path }
        )
      },
    })
  },
  showServiceModal() {
    if (this.serviceModal) {
      this.serviceModal.show()
    }
  },
  /**
   * 查看图片
   */
  handlePreview() {
    const { qrcode } = this.data
    wx.previewImage({
      current: qrcode,
      urls: [qrcode],
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.wuliuModal = this.selectComponent('#wuliuModal')
    this.serviceModal = this.selectComponent('#serviceModal')
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    wx.pageScrollTo({
      scrollTop: 0,
      duration: 0,
    })
    this.setData({
      current: 1,
    })
    this.getSourceList()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    console.log('下拉了')
    let { current, total } = this.data
    // 总页码
    const pages = total / 10
    if (current < pages) {
      this.setData({
        current: current + 1,
      })
      this.getUserDiscount()
    } else {
      wx.showToast({
        title: '没有更多了',
        icon: 'error',
      })
    }
  },

  // 拨打电话
  call() {
    wx.makePhoneCall({
      phoneNumber: '0371-53376036'
    })
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage(e) {
    return shareOptions('default', e)
  },
})
